package kr.hkit.androidcomplete03.ch25;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SQLiteTest extends Activity {
	
	WordDbHelper mHelper;
	ListView list;
	WordDAO dao;
	SimpleCursorAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqllite_test);
		
		mHelper = new WordDbHelper(this);
		list = (ListView) findViewById(R.id.orderListView);
		dao = WordDAO.open(this);
	}
	
	public void mOnClick(View v){
		boolean result;
		String str = null;
		
		switch(v.getId()){
		
		case R.id.insertBtn:
			EditText eng = (EditText) findViewById(R.id.engEdit);
			EditText han = (EditText)findViewById(R.id.hanEdit);
			result = dao.insert(eng.getText().toString(), han.getText().toString());
			str = result ? "insert Success" : "insert False";
			eng.setText("");
			han.setText("");
			break;
			
		case R.id.deleteAllBtn:
			result = dao.deleteAll();
			str = result ? "DeleteAll Success" : "DeleteAll Fail";
			break;
			
		case R.id.deleteBtn:
			EditText num = (EditText)findViewById(R.id.numEdit);			// 입력한 id값에 해당하는 데이터 삭제
			int idx = Integer.parseInt(num.getText().toString());
			result = dao.delete(idx);
			str = result ? "Delete Success" : "Delete Fail";
			break;
			
		case R.id.updateBtn:
			EditText updateNum = (EditText) findViewById(R.id.numUpdate);
			EditText updateEng = (EditText) findViewById(R.id.engUpdate);
			EditText updateHan = (EditText) findViewById(R.id.hanUpdate);
			int id = Integer.parseInt(updateNum.getText().toString());
			
			result = dao.update(id, updateEng.getText().toString(), updateHan.getText().toString());
			str = result ? "Update Success" : "Update Fail";
			updateNum.setText("");
			updateEng.setText("");
			updateHan.setText("");
			break;
			
		case R.id.selectBtn:
			// 현재 DB에 저장된 데이터 보여주기
			Cursor cursor = dao.selectAll();
			//startManagingCursor(cursor);
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.listrow, 
					cursor, 
					new String[] { "_id", "eng", "han" }, 
					new int[] { R.id.listnum, R.id.listeng,	R.id.listhan });
			list.setAdapter(adapter);
			str = "Select Success";
			break;
		}
		
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}
	
	// 자주 열고 닫을 떄 사용
	@Override
	protected void onPause() {
		super.onPause();
		dao.close();
	}
}
